package com.txby.platformApi.component.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.jck.mybatis.log.GlobalLogAnnotation;
import com.jck.mybatis.util.PageBean;
import com.jck.mybatis.util.PageList;
import com.jck.tools.ChkUtil;
import com.txby.platformCore.component.service.CommonController;
import com.txby.platformCore.component.util.YoukuVideoUtils;
import com.txby.platformCore.data.CommonApiModelMapExt;
import com.txby.platformCore.entity.CheckSickroom;
import com.txby.platformCore.entity.DctNrsCardCnf;
import com.txby.platformCore.entity.SickDetailInfo;
import com.txby.platformCore.entity.SickSuggestion;
import com.txby.platformCore.entity.SysStock;
import com.txby.platformCore.entity.SysStockIn;
import com.txby.platformCore.entity.SysStockOut;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
* @author 作者 jacking
* @date  
 */
@SuppressWarnings("all")
@RestController
@Api(value="api",description="api-说明")
@RequestMapping("/api")
public class ApiController extends CommonController{
	private static Logger log = Logger.getLogger(ApiController.class);
	
	@ApiOperation(value = "患者反馈的保存", notes = "患者反馈的保存-说明")
	@PostMapping("/saveSickFeedBack/{type}/{token}")
/*	@ApiImplicitParams({
		@ApiImplicitParam(paramType="query",dataType="number",name="type",value="请求端（ 0:web,1:android,2:iphone）",required=true),
		@ApiImplicitParam(paramType="query",dataType="string",name="token",value="用户令牌",required=true),
		@ApiImplicitParam(paramType="query",dataType="string",name="bedNO",value="患者床号",required=true),
		@ApiImplicitParam(paramType="query",dataType="string",name="sickAreaNO",value="床位病区号",required=true),
		@ApiImplicitParam(paramType="query",dataType="string",name="inHosNO",value="住院号",required=true),
		@ApiImplicitParam(paramType="query",dataType="string",name="isHide",value="是否匿名",required=true),
		@ApiImplicitParam(paramType="query",dataType="string",name="content",value="建议内容",required=true)
	})
	@GlobalLogAnnotation(logType=2,discription="保存患者反馈信息")*/
	public Map saveSickFeedBack(@PathVariable("type") Integer type, @PathVariable("token") String token,@RequestParam(required=true) String content, 
			@RequestParam(required=true) String isHide,@RequestParam(required=true,name="deviceSN") String deviceSN ) {
		CommonApiModelMapExt mm = chekTokenCahceValid(token, type);
		try {
			if (!isTokenValid) {
				return mm;
			}
			SickSuggestion ss =  new SickSuggestion();
			ss.setContent(content);
			ss.setIsHide(isHide);
			this.mBaseDao.saveObject(ss);
			mm.put(CommonApiModelMapExt.ERRCODE, 0);
			mm.put(CommonApiModelMapExt.ERRMSG, "保存成功");
			return mm;
		} catch (Exception e) {
			e.printStackTrace();
			mm.put(CommonApiModelMapExt.ERRCODE, 1);
			mm.put(CommonApiModelMapExt.ERRMSG, "系统异常");
		}
		return mm;
	}
	
	@ApiOperation(value = "护士录入查房信息", notes = "护士录入查房信息-说明")
	@PostMapping("/callNurseSickRoom/{type}/{token}")
/*	@ApiImplicitParams({
		@ApiImplicitParam(paramType="query",dataType="number",name="type",value="请求端（ 0:web,1:android,2:iphone）",required=true),
		@ApiImplicitParam(paramType="query",dataType="string",name="token",value="用户令牌",required=true),
		@ApiImplicitParam(paramType="query",dataType="string",name="bedNO",value="患者床号",required=true),
		@ApiImplicitParam(paramType="query",dataType="string",name="sickAreaNO",value="床位病区号",required=true),
		@ApiImplicitParam(paramType="query",dataType="string",name="inHosNO",value="住院号",required=true),
		@ApiImplicitParam(paramType="query",dataType="string",name="isHide",value="是否匿名",required=true),
		@ApiImplicitParam(paramType="query",dataType="string",name="checkRecord",value="查房记录",required=true)
	})
	@GlobalLogAnnotation(logType=2,discription="护士录入查房信息")*/
	public Map callNurseSickRoom(@PathVariable("type") Integer type, @PathVariable("token") String token,@RequestParam(required=true,name="checkRecord") String checkRecord,
			@RequestParam(required=true,name="deviceSN") String deviceSN,@RequestParam(required=true,name="cardNO") String cardNO) {
//		CommonApiModelMapExt mm = chekTokenCahceValid(token, type);
		CommonApiModelMapExt mm = new CommonApiModelMapExt();
		SickDetailInfo sdi;
		try {
			if (!true) {
				return mm;
			}
			DctNrsCardCnf dcc=getDctNrsCardCnfInfo(cardNO);
			if(dcc == null) {
				mm.put(CommonApiModelMapExt.ERRCODE, 4200);
				mm.put(CommonApiModelMapExt.ERRMSG, "请求参数有误");
				return mm;
			}
			
			sdi = getSickDetailInfo(deviceSN);
			CheckSickroom cs = new CheckSickroom();
			cs.setBedNO(sdi.getBedNO());
			cs.setCheckRecord(checkRecord);
			cs.setMgBedNurse(dcc.getCardNO());
			cs.setMgBedNurse(cardNO);
			cs.setDeptId(dcc.getDeptId());
			cs.setCheckTime(new Date());
			if (cs != null) {
				this.mBaseDao.saveObject(cs);
				mm.put(CommonApiModelMapExt.ERRCODE, 0);
				mm.put(CommonApiModelMapExt.ERRMSG, "保存成功");
				return mm;
			} 
		} catch (Exception e) {
			e.printStackTrace();
			mm.put(CommonApiModelMapExt.ERRCODE, 1);
			mm.put(CommonApiModelMapExt.ERRMSG, "系统异常");
		}
		return mm;
	}
	
	@GetMapping("/getNurseNotesDayList/{type}/{token}")
	public Map getInHosBillDayList(@PathVariable("type") Integer type, @PathVariable("token") String token,@RequestParam(required=true,name="deviceSN") String deviceSN) {
		CommonApiModelMapExt mm = chekTokenCahceValid(token, type);
		try {
			if (!true) {
				return mm;
			}
			PageList pl=new PageList<>();
			SickDetailInfo sdi = getSickDetailInfo(deviceSN);
			String bedNo = sdi.getBedNO();
			Map paramMap = new HashMap<>();
			String searchSql = " and date_format(checkTime, '%Y-%m-%d')<=date_format(now(), '%Y-%m-%d')";
			if (!ChkUtil.isEmpty(bedNo)) {
				bedNo = bedNo.trim();
				if (bedNo.contains("%") || bedNo.contains("_")) {
					bedNo = bedNo.trim().replace("%", "\\%").replace("_", "\\_");
					searchSql += " and bedNo = #{pojo.bedNo} escape '\\'";
					paramMap.put("bedNo", bedNo);
				} else {
					searchSql += " and bedNo = #{pojo.bedNo} ";
					paramMap.put("bedNo", bedNo);
				}
			}
			
			searchSql += " order by daily desc ";//默认时间倒序
			
			pl = this.mBaseDao.findBySqlForPageList("select  distinct date_format(checkTime, '%Y-%m-%d') daily from  "+mBaseDao.tableName(CheckSickroom.class)+" where 1=1  "+searchSql, Map.class, null, paramMap);
			if(pl==null || pl.getResultList()==null || pl.getResultList().size()==0) {
				mm.put(CommonApiModelMapExt.ERRCODE, 4500);
				mm.put(CommonApiModelMapExt.ERRMSG, "查询成功");
				mm.put("data", pl.getResultList());
				return mm;
			}
			mm.put(CommonApiModelMapExt.ERRCODE, 0);
			mm.put(CommonApiModelMapExt.ERRMSG, "查询成功");
			mm.put("data", pl.getResultList());
			return mm;
		} catch (Exception e) {
			e.printStackTrace();
			mm.put(CommonApiModelMapExt.ERRCODE, 5000);
			mm.put(CommonApiModelMapExt.ERRMSG, "系统异常");
		}
		return mm;
	}
	
	
	
	@GetMapping("/getNurseNotes/{type}/{token}")
	public CommonApiModelMapExt getNurseNotes(@PathVariable("type") Integer type, @PathVariable("token") String token,@RequestParam(required=false,name="checkTime") String checkTime,
			Integer pageSize,Integer curPage,@RequestParam(required=true,name="deviceSN") String deviceSN) {
		CommonApiModelMapExt mm = chekTokenCahceValid(token, type);
		SickDetailInfo sdi;
		try {
			if (!true) {
				return mm;
			}
			// 业务必须字段非空校验
			if(ChkUtil.isEmpty(deviceSN)) {
				mm.put(CommonApiModelMapExt.ERRCODE, 4200);
				mm.put(CommonApiModelMapExt.ERRMSG, "请求参数有误");
				return mm;
			}
			sdi = getSickDetailInfo(deviceSN);
			Map paramMap = new HashMap<>();
			String searchSql = "";
		
			
			if (!ChkUtil.isEmpty(sdi.getBedNO())) {
				searchSql += " and bedNO =  #{pojo.bedNO} ";
				paramMap.put("bedNO", sdi.getBedNO());
			}
			
			if (!ChkUtil.isEmpty(checkTime)) {
				searchSql += " and date_format(checkTime, '%Y-%m-%d') = #{pojo.checkTime} ";
				paramMap.put("checkTime", checkTime);
			}
			searchSql += " order by checkTime desc";// 时间倒序排序
			PageList pl=new PageList<>();
			PageBean pb = new PageBean();
			if(!ChkUtil.isEmpty(curPage)) {
				pb.setCurrentPage(curPage);
			} 
			if(!ChkUtil.isEmpty(pageSize)) {
				pb.setPageSize(pageSize);
			} 
			pl = this.mBaseDao.findBySqlForPageList("select checkRecord,checkTime,mgBedNurse from  "+mBaseDao.tableName(CheckSickroom.class)+" where 1=1  "+searchSql, Map.class, pb, paramMap);
			if(pl==null || pl.getResultList()==null || pl.getResultList().size()==0) {
				mm.put(CommonApiModelMapExt.ERRCODE, 4500);
				mm.put(CommonApiModelMapExt.ERRMSG, "查询成功");
				mm.put("data", pl.getResultList());
				return mm;
			}
			List l = pl.getResultList();
			
			for(Object o:l) {
				Map m = (Map)o;
				DctNrsCardCnf dcc=getDctNrsCardCnfInfo(m.get("mgBedNurse")+"");
				m.put("mgBedNurse",dcc.getName());
//				l.add(m);
			}
			/**
			 * 请求http数据api
			 */
			mm.put(CommonApiModelMapExt.ERRCODE, 0);
			mm.put(CommonApiModelMapExt.ERRMSG, "查询成功");
			mm.put("data", l);
			return mm;
			
		} catch (Exception e) {
			e.printStackTrace();
			mm.put(CommonApiModelMapExt.ERRCODE, 5000);
			mm.put(CommonApiModelMapExt.ERRMSG, "系统异常");
		}
		
		return mm;
	}
	
	
	@ApiOperation(value = "保存视频", notes = "保存视频-说明")
	@PostMapping("/saveSickVideoJson/{type}/{token}")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType="query",dataType="number",name="type",value="请求端（ 0:web,1:android,2:iphone）",required=true),
		@ApiImplicitParam(paramType="query",dataType="string",name="token",value="用户令牌",required=true)
	})
	@GlobalLogAnnotation(logType=2,discription="保存视频")
	public Map saveSickVideoJson(@PathVariable("type") Integer type, @PathVariable("token") String token) {
		CommonApiModelMapExt mm = chekTokenCahceValid(token, type);
		
		CloseableHttpResponse response=null;
		CloseableHttpClient httpClient=null;
		try {
			if (!isTokenValid) {
				return mm;
			}
			// list
	        httpClient =YoukuVideoUtils.createSSLClientDefault();   
	        HttpGet httpGet=null;
	        List<NameValuePair> params=new ArrayList<NameValuePair>();
	        params.add(new BasicNameValuePair("client_id",YoukuVideoUtils.CLIENT_ID));
	        params.add(new BasicNameValuePair("access_token",YoukuVideoUtils.ACCESS_TOKEN));
	        httpGet= YoukuVideoUtils.getHttpGet("https","api.youku.com",-1,"/videos/by_me.json",params,null);
	        response=httpClient.execute(httpGet);
	        //打印响应的到的html正文
	        HttpEntity entity =response.getEntity();
	        String html=EntityUtils.toString(entity);
	        Map m=JSON.parseObject(html, Map.class);
	        //关闭连接
	        response.close();
	        httpClient.close();
			
			if (m != null) {
				this.mBaseDao.saveObject(m);
				mm.put(CommonApiModelMapExt.ERRCODE, 0);
				mm.put(CommonApiModelMapExt.ERRMSG, "保存成功");
				return mm;
			} else {
				mm.put(CommonApiModelMapExt.ERRCODE, 0);
				mm.put(CommonApiModelMapExt.ERRMSG, "保存成功");
				return mm;
			} 
		} catch (Exception e) {
			e.printStackTrace();
			mm.put(CommonApiModelMapExt.ERRCODE, 1);
			mm.put(CommonApiModelMapExt.ERRMSG, "系统异常");
		} finally {
	        try {
				response.close();
				httpClient.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return mm;
	}
	
	@ApiOperation(value = "获取单个视频", notes = "获取单个视频-说明")
	@PostMapping("/getSickVideoJson/{type}/{token}")
	@ApiImplicitParams({
		@ApiImplicitParam(paramType="query",dataType="number",name="type",value="请求端（ 0:web,1:android,2:iphone）",required=true),
		@ApiImplicitParam(paramType="query",dataType="string",name="token",value="用户令牌",required=true),
		@ApiImplicitParam(paramType="query",dataType="string",name="videoId",value="视频Id",required=true)
	})
	@GlobalLogAnnotation(logType=2,discription="获取单个视频")
	public Map getSickVideoJson(@PathVariable("type") Integer type, @PathVariable("token") String token,@RequestParam("videoId") String videoId) {
		CommonApiModelMapExt mm = chekTokenCahceValid(token, type);
		CloseableHttpResponse response1=null;
		CloseableHttpClient httpClient1=null;
		try {
	    	// 单个	https://api.youku.com/videos/show.json
	        httpClient1 =YoukuVideoUtils.createSSLClientDefault();   
	        HttpGet httpGet1=null;
	        List<NameValuePair> params1=new ArrayList<NameValuePair>();
	        params1.add(new BasicNameValuePair("client_id",YoukuVideoUtils.CLIENT_ID));
	        params1.add(new BasicNameValuePair("video_id", videoId));
	        httpGet1= YoukuVideoUtils.getHttpGet("https","api.youku.com",-1,"/videos/show.json",params1,null);
	        response1=httpClient1.execute(httpGet1);
	        //打印响应的到的html正文
	        HttpEntity entity1 =response1.getEntity();
	        String html1=EntityUtils.toString(entity1);
	        System.out.println(html1);
			mm.put("data", html1);
	        //关闭连接
	        response1.close();
	        httpClient1.close();
		} catch (Exception e) {
			e.printStackTrace();
			mm.put(CommonApiModelMapExt.ERRCODE, 1);
			mm.put(CommonApiModelMapExt.ERRMSG, "系统异常");
		} finally {
	        //关闭连接
			try {
				httpClient1.close();
				response1.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
		return mm;
	}
	
	/**
	 * 
	* @Title: getStockDeptAndMarque
	* @Description: 获取部门和产品型号
	* @param @param type
	* @param @param token
	* @param @param deviceSN
	* @param @return    设定文件 
	* @return Map    返回类型 
	* @throws
	 */
	@GetMapping("/stock/getStockDeptAndMarque/{type}/{token}")
	public Map getStockDeptAndMarque(@PathVariable("type") Integer type, @PathVariable("token") String token,@RequestParam(required=true,name="deviceSN") String deviceSN) {
		CommonApiModelMapExt mm = chekTokenCahceValid(token, type);
		try {
			if (!true) {
				return mm;
			}
			Map paramMap = new HashMap<>();
			List deptList = this.mBaseDao.findBySql("select dept_id deptId, name deptName from  sys_dept where type=6", Map.class, null);
			paramMap.put("deptList", deptList);
			
			String sql="SELECT t.typeNo typeNo,t.typeNo typeName FROM  "+this.mBaseDao.tableName(SysStock.class)+" t " ;
			List typeList=mBaseDao.findBySql(sql, SysStock.class, null);
			paramMap.put("typeList", typeList);
			
			if(deptList==null ||deptList.size()==0 || typeList==null || typeList.size()==0) {
				mm.put(CommonApiModelMapExt.ERRCODE, 4500);
				mm.put(CommonApiModelMapExt.ERRMSG, "查询成功");
				return mm;
			}

			mm.put(CommonApiModelMapExt.ERRCODE, 0);
			mm.put(CommonApiModelMapExt.ERRMSG, "查询成功");
			mm.put("data", paramMap);
			return mm;
		} catch (Exception e) {
			e.printStackTrace();
			mm.put(CommonApiModelMapExt.ERRCODE, 5000);
			mm.put(CommonApiModelMapExt.ERRMSG, "系统异常");
		}
		return mm;
	}
	
	/**
	* @Title: saveStockIn 
	* @Description: 保存产品入库信息
	* @param @param type
	* @param @param token
	* @param @param sns
	* @param @param deptId
	* @param @param typeNo
	* @param @param deviceSN
	* @param @return    设定文件 
	* @return Map    返回类型 
	* @throws
	 */
	@ApiOperation(value = "入库", notes = "入库-说明")
	@PostMapping("/stock/saveStockIn/{type}/{token}")
	public Map saveStockIn(@PathVariable("type") Integer type, @PathVariable("token") String token,
			@RequestParam(required=true,name="stockIns") String sns,
			@RequestParam(required=true,name="deptId") String deptId,
			@RequestParam(required=true,name="userId") String userId,
			@RequestParam(required=true,name="typeNo") String typeNo,
			@RequestParam(required=true,name="deviceSN") String deviceSN) {
		CommonApiModelMapExt mm = new CommonApiModelMapExt();
		try {
			if (!true) {
				return mm;
			}
			
			JSONArray o=(JSONArray) JSONArray.parse(sns);
			Object[] snsArr = o.toArray();
			SysStockIn ssi=null;
			for(int i=0;i<snsArr.length;i++) {
				ssi = new SysStockIn();
				ssi.setTypeNo(typeNo);
				ssi.setDeptId(Long.valueOf(deptId));
				ssi.setDeviceSN(snsArr[i]+"");
				ssi.setStatus(0);
				ssi.setStockInOper(userId);
				mBaseDao.saveObject(ssi);
			}
			mm.put(CommonApiModelMapExt.ERRCODE, 0);
			mm.put(CommonApiModelMapExt.ERRMSG, "保存成功");
			return mm;
		} catch (Exception e) {
			e.printStackTrace();
			mm.put(CommonApiModelMapExt.ERRCODE, 1);
			mm.put(CommonApiModelMapExt.ERRMSG, "系统异常");
		}
		return mm;
	}
	
	/**
	* @Title: saveStockOut 
	* @Description: 保存产品出库信息
	* @param @param type
	* @param @param token
	* @param @param sns
	* @param @param deptId
	* @param @param typeNo
	* @param @param deviceSN
	* @param @return    设定文件 
	* @return Map    返回类型 
	* @throws
	 */
	@ApiOperation(value = "出库", notes = "出库-说明")
	@PostMapping("/stock/saveStockOut/{type}/{token}")
	public Map saveStockOut(@PathVariable("type") Integer type, @PathVariable("token") String token,
			@RequestParam(required=true,name="stockIns") String sns,
			@RequestParam(required=true,name="deptId") String deptId,
			@RequestParam(required=true,name="userId") String userId,
			@RequestParam(required=true,name="typeNo") String typeNo,
			@RequestParam(required=true,name="deviceSN") String deviceSN) {
		CommonApiModelMapExt mm = new CommonApiModelMapExt();
		try {
			if (!true) {
				return mm;
			}
			
			JSONArray o=(JSONArray) JSONArray.parse(sns);
			Object[] snsArr = o.toArray();
			SysStockOut sso=null;
			for(int i=0;i<snsArr.length;i++) {
				sso = new SysStockOut();
				sso.setTypeNo(typeNo);
				sso.setDeptId(Long.valueOf(deptId));
				sso.setDeviceSN(snsArr[i]+"");
				sso.setStatus(0);
				sso.setStockOutOper(userId);
				mBaseDao.saveObject(sso);
			}
			mm.put(CommonApiModelMapExt.ERRCODE, 0);
			mm.put(CommonApiModelMapExt.ERRMSG, "保存成功");
			return mm;
		} catch (Exception e) {
			e.printStackTrace();
			mm.put(CommonApiModelMapExt.ERRCODE, 1);
			mm.put(CommonApiModelMapExt.ERRMSG, "系统异常");
		}
		return mm;
	}
	

	/**
	 * 
	* @Title: saveStock 
	* @Description: 保存产品入库或者出库信息
	* @param @param type
	* @param @param token
	* @param @param sns
	* @param @param userId
	* @param @param operFlag
	* @param @param deviceSN
	* @param @return    设定文件 
	* @return Map    返回类型 
	* @throws
	 */
	@ApiOperation(value = "出库", notes = "出库-说明")
	@PostMapping("/stock/saveStock/{type}/{token}")
	public Map saveStock(@PathVariable("type") Integer type, @PathVariable("token") String token,
			@RequestParam(required=true,name="deviceSN") String deviceSN,
			@RequestParam(required=true,name="sns") String sns,
			@RequestParam(required=false,name="userId") String userId,
			@RequestParam(required=true,name="operFlag") String operFlag) {
		CommonApiModelMapExt mm = new CommonApiModelMapExt();
		try {
			if (!true) {
				return mm;
			}
			
/*			JSONArray o=(JSONArray) JSONArray.parse(sns);
			Object[] snsArr = o.toArray();*/
			Object[] snsArr = sns.split(",");
			if("0".equals(operFlag)) { // 入库
				SysStockIn ssi=null;
				for(int i=0;i<snsArr.length;i++) {
					ssi = new SysStockIn();
					ssi.setDeviceSN(snsArr[i]+"");
					ssi.setStatus(1);
					ssi.setStockStatus(1);
					ssi.setStockInOper(userId);
					mBaseDao.saveObject(ssi);
				}
				
			} else if("1".equals(operFlag)){ // 出库
				SysStockOut sso=null;
				for(int i=0;i<snsArr.length;i++) {
					sso = new SysStockOut();
					sso.setDeviceSN(snsArr[i]+"");
					sso.setStatus(1);
//					sso.setStockStatus(3);
					sso.setStockOutOper(userId);
					mBaseDao.saveObject(sso);
				}
			}
			
			mm.put(CommonApiModelMapExt.ERRCODE, 0);
			mm.put(CommonApiModelMapExt.ERRMSG, "保存成功");
			return mm;
		} catch (Exception e) {
			e.printStackTrace();
			mm.put(CommonApiModelMapExt.ERRCODE, 1);
			mm.put(CommonApiModelMapExt.ERRMSG, "系统异常");
		}
		return mm;
	}
	
	
	
}